package com.wcs.spring.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

/**
 * <p>
 * Title: Phicomm_[子系统统名]_[模块名]
 * </p>
 * <p>
 * Description: [描述该类概要功能介绍]
 * </p>
 * 
 * @author hexuan2014
 * @version $Revision$ 2014-9-18
 * @author (lastest modification by $Author$)
 * @since 1.0
 */
public class DateConverter implements Converter<String, Date> {
	private static Logger logger = LoggerFactory.getLogger(DateConverter.class);

	private List<String> patterns = new ArrayList<String>();

	public DateConverter() {
		// patterns.add("yyyy-MM-dd");
		patterns.add("yyyy-MM-dd HH:mm:ss");
		patterns.add("yyyy-MM-dd");
	}

	@Override
	public Date convert(String text) {
		if (text == null) {
			return null;
		}

		for (String pattern : patterns) {
			Date date = tryConvert(text, pattern);

			if (date != null) {
				return date;
			}
		}

		return null;
	}

	public Date tryConvert(String text, String pattern) {
		DateFormat dateFormat = new SimpleDateFormat(pattern);
		dateFormat.setLenient(false);

		try {
			try {
				return dateFormat.parse(text);
			}
			catch (java.text.ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		catch (Exception ex) {
			logger.debug(ex.getMessage(), ex);
		}

		return null;
	}

	public void setPatterns(List<String> patterns) {
		this.patterns = patterns;
	}
}
